import tensorflow as tf
import numpy as np

# 数据加载功能
(train_x,train_y),(test_x,test_y)=tf.keras.datasets.mnist.load_data()

train_x=train_x.reshape([-1,28,28,1])/255
test_x=test_x.reshape([-1,28,28,1])/255


'''
1.卷积， 卷积核3*3， 步长1， 做0补边
2.池化， 池化核2*2， 步长2   0补边
3.卷积， 卷积核3*3， 步长1   0补边
4.池化， 池化核2*2   步长2   0补边
5 使用全连接，进行模型分类
'''
print(train_x.shape)
model=tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(32,kernel_size=(3,3),strides=1,padding='same')) # 28 * 28 * 32
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.MaxPool2D(pool_size=(2,2),strides=2,padding='same')) # 14 * 14 * 32
model.add(tf.keras.layers.Conv2D(64,kernel_size=(3,3),strides=1,padding='same')) # 14 * 14 * 64
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.MaxPool2D(pool_size=(2,2),strides=2,padding='same')) # 7 * 7 * 64
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(10))
model.add(tf.keras.layers.Activation('softmax'))

model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.01),
              loss=tf.keras.losses.SparseCategoricalCrossentropy(),  #输入无需独热
              metrics=['accuracy'])

model.fit(train_x,train_y,batch_size=64,epochs=5)
model.evaluate(test_x,test_y)

